package info.batcloud.fanli.api.controller;

import info.batcloud.fanli.api.security.annotation.UserLevelRequire;
import info.batcloud.fanli.api.vo.CommissionItemShareSvgVo;
import info.batcloud.fanli.core.dto.CommissionItemDTO;
import info.batcloud.fanli.core.dto.UserCommissionItemShareDTO;
import info.batcloud.fanli.core.domain.BusinessResponse;
import info.batcloud.fanli.core.enums.EcomPlat;
import info.batcloud.fanli.core.enums.UserLevel;
import info.batcloud.fanli.core.helper.SecurityHelper;
import info.batcloud.fanli.core.service.CommissionItemService;
import info.batcloud.fanli.core.service.CommissionItemSharePicGenService;
import info.batcloud.fanli.core.service.UserCommissionItemShareService;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/commission-item")
public class CommissionItemController {

    @Inject
    private CommissionItemService commissionItemService;


    @Inject
    private CommissionItemSharePicGenService commissionItemSharePicGenService;

    @Inject
    private UserCommissionItemShareService userCommissionItemShareService;

    @GetMapping("/{id}")
    @ResponseBody
    public Object show(@PathVariable long id) {
        CommissionItemInfo ci = new CommissionItemInfo();
        CommissionItemDTO item = commissionItemService.findById(id);
        ci.setTitle(item.getTitle());
        ci.setItemImgs(new HashSet<>());
        ci.getItemImgs().addAll(Arrays.asList(item.getPicUrl()));
        ci.getItemImgs().addAll(item.getImgList());
        ci.setOriginPrice(item.getOriginPrice());
        ci.setPrice(item.getPrice());
        ci.setEcomPlat(item.getEcomPlat());
        ci.setCouponValue(item.getCouponValue());
        ci.setFavor(false);
        ci.setSales(item.getSales());
        ci.setShopcatId(item.getShopcatId());
        ci.setCoupon(item.isCoupon());
        ci.setTbkZt(item.isTbkZt());
        return BusinessResponse.ok(ci);
    }

    @GetMapping("/share-pic/generate/{id}")
    @PreAuthorize("hasRole('USER')")
    @UserLevelRequire(UserLevel.PLUS)
    public String sharePicGenPage(@PathVariable long id, ModelMap map, HttpServletRequest request) {
        CommissionItemDTO ci = commissionItemService.findById(id);
        UserCommissionItemShareDTO shareDto =
                userCommissionItemShareService.findValidUserCommissionItemShare(id, SecurityHelper.loginUserId());
        CommissionItemShareSvgVo svgModel = new CommissionItemShareSvgVo();
        svgModel.setPrice(ci.getPrice());
        svgModel.setUrl(StringUtils.isNotBlank(shareDto.getShortUrl()) ? shareDto.getShortUrl() : shareDto.getUrl());
        svgModel.setOriginPrice(ci.getOriginPrice());
        svgModel.setCouponValue(ci.getCouponValue());
        svgModel.setTitle(ci.getTitle());
        svgModel.setEconPlatName(ci.getEcomPlat().getTitle());
        map.put("svg", svgModel);
        return "commission-item/gen-share-pic";
    }

    @GetMapping("/share-pic/{id}-{userId}")
    public String sharePicGenPic(@PathVariable long id, @PathVariable long userId, @RequestParam(required = false) String picUrl, HttpServletResponse response) throws IOException {
        response.setContentType("image/jpg");
        response.setHeader("Content-Type", "image/jpg");
        try {
            commissionItemSharePicGenService.genSharePic(id, userId, picUrl, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.getOutputStream().close();
        response.flushBuffer();
        return null;
    }

    @GetMapping("/share-pic-svg/{id}-{userId}")
    public String sharePicGenSvg(@PathVariable long id, @PathVariable long userId, @RequestParam(required = false) String picUrl, ModelMap map, HttpServletResponse response) throws IOException {
        map.put("svg", commissionItemSharePicGenService.genSharePicSvgXml(id, userId, picUrl));
        return "svg";
    }

    @GetMapping("/go-to-buy/{id}")
    @ResponseBody
    @PreAuthorize("hasRole('USER')")
    public Object goToBuyParam(@PathVariable long id) {
         return BusinessResponse.ok(commissionItemService.findBuyParams(id, SecurityHelper.loginUserId()));
    }

    @GetMapping("/share-info/{id}")
    @ResponseBody
    @PreAuthorize("hasRole('USER')")
    @UserLevelRequire(UserLevel.PLUS)
    public Object shareInfo(@PathVariable long id) {

        CommissionItemInfo ci = new CommissionItemInfo();
        CommissionItemDTO item = commissionItemService.findById(id);
        ci.setTitle(item.getTitle());
        ci.setItemImgs(new HashSet<>());
        ci.getItemImgs().addAll(Arrays.asList(item.getPicUrl().split(",")));
        ci.getItemImgs().addAll(item.getImgList());
        ci.setOriginPrice(item.getOriginPrice());
        ci.setPrice(item.getPrice());
        ci.setEcomPlat(item.getEcomPlat());
        ci.setCouponValue(item.getCouponValue());
        ci.setFavor(false);
        ci.setSales(item.getSales());
        Map<String, Object> map = new HashMap<>();
        map.put("item", ci);
        map.put("shareInfo", commissionItemService.findShareInfo(id, SecurityHelper.loginUserId()));
        return BusinessResponse.ok(map);
    }

    public static class CommissionItemInfo {
        private long id;
        private String title;
        private String picUrl;
        private Set<String> itemImgs;
        private Float originPrice;
        private Float price;
        private Float couponValue;
        private EcomPlat ecomPlat;
        private boolean favor;
        private int sales;
        private Long shopcatId;
        private boolean coupon;
        private boolean tbkZt;

        public boolean isTbkZt() {
            return tbkZt;
        }

        public void setTbkZt(boolean tbkZt) {
            this.tbkZt = tbkZt;
        }

        public boolean isCoupon() {
            return coupon;
        }

        public void setCoupon(boolean coupon) {
            this.coupon = coupon;
        }

        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public String getPicUrl() {
            return picUrl;
        }

        public void setPicUrl(String picUrl) {
            this.picUrl = picUrl;
        }

        public Long getShopcatId() {
            return shopcatId;
        }

        public void setShopcatId(Long shopcatId) {
            this.shopcatId = shopcatId;
        }

        public int getSales() {
            return sales;
        }

        public void setSales(int sales) {
            this.sales = sales;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public Set<String> getItemImgs() {
            return itemImgs;
        }

        public void setItemImgs(Set<String> itemImgs) {
            this.itemImgs = itemImgs;
        }

        public Float getOriginPrice() {
            return originPrice;
        }

        public void setOriginPrice(Float originPrice) {
            this.originPrice = originPrice;
        }

        public Float getPrice() {
            return price;
        }

        public void setPrice(Float price) {
            this.price = price;
        }

        public Float getCouponValue() {
            return couponValue;
        }

        public void setCouponValue(Float couponValue) {
            this.couponValue = couponValue;
        }

        public EcomPlat getEcomPlat() {
            return ecomPlat;
        }

        public void setEcomPlat(EcomPlat ecomPlat) {
            this.ecomPlat = ecomPlat;
        }

        public boolean isFavor() {
            return favor;
        }

        public void setFavor(boolean favor) {
            this.favor = favor;
        }
    }

}
